<template>
  <el-date-picker v-model="state.dateRange" :value-format="timeFormat" format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
    range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="state.shortcuts"
    @change="handleChange" clearable />
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { reactive, watch } from 'vue'
import type { PropType } from 'vue'

const emit = defineEmits(['update:startDate', 'update:endDate'])

const props = defineProps({
  startDate: {
    type: String as PropType<string | null>,
    default: null
  },
  endDate: {
    type: String as PropType<string | null>,
    default: null
  }
})

const timeFormat = 'YYYY-MM-DD HH:mm:ss'

const state = reactive({
  dateRange: [props.startDate, props.endDate] as [string | null, string | null],
  shortcuts: [
    {
      text: '最近一年',
      value: () => [
        dayjs().subtract(1, 'year').startOf('day').format(timeFormat),
        dayjs().endOf('day').format(timeFormat)
      ]
    },
    {
      text: '最近半年',
      value: () => [
        dayjs().subtract(6, 'month').startOf('day').format(timeFormat),
        dayjs().endOf('day').format(timeFormat)
      ]
    },
    {
      text: '最近三月',
      value: () => [
        dayjs().subtract(3, 'month').startOf('day').format(timeFormat),
        dayjs().endOf('day').format(timeFormat)
      ]
    },
    {
      text: '最近一月',
      value: () => [
        dayjs().subtract(1, 'month').startOf('day').format(timeFormat),
        dayjs().endOf('day').format(timeFormat)
      ]
    },
    {
      text: '最近一周',
      value: () => [
        dayjs().subtract(7, 'day').startOf('day').format(timeFormat),
        dayjs().endOf('day').format(timeFormat)
      ]
    },
    {
      text: '最近三天',
      value: () => [
        dayjs().subtract(3, 'day').startOf('day').format(timeFormat),
        dayjs().endOf('day').format(timeFormat)
      ]
    },
    {
      text: '今天',
      value: () => [
        dayjs().startOf('day').format(timeFormat),
        dayjs().endOf('day').format(timeFormat)
      ]
    },
    {
      text: '此刻',
      value: () => {
        const now = dayjs().format(timeFormat)
        return [now, now]
      }
    }
  ]
})

const handleChange = (value: [string, string] | null) => {
  if (value) {
    const [start, end] = value
    emit('update:startDate', start)
    emit('update:endDate', end)
  } else {
    // 处理清除操作
    emit('update:startDate', null)
    emit('update:endDate', null)
    state.dateRange = [null, null] // 确保本地状态重置
  }
}

// 同步父组件传值变化
watch(
  () => [props.startDate, props.endDate],
  ([newStart, newEnd]) => {
    if (newStart !== state.dateRange[0] || newEnd !== state.dateRange[1]) {
      state.dateRange = [newStart, newEnd]
    }
  },
  { deep: true }
)
</script>